package com.haierp.controller;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
import com.haierp.enums.OrderStatus;
import com.haierp.enums.StockUpStatus;
import com.haierp.exception.ErpCommonException;
import com.haierp.exception.InventoryException;
import com.haierp.mapper.OuterOrderDetailMapper;
import com.haierp.mapper.OuterOrderMapper;
import com.haierp.model.ErpOrder;
import com.haierp.model.Seller;
import com.haierp.model.purchase.PurchaseStorageDetail;
import com.haierp.model.sale.OuterOrder;
import com.haierp.model.sale.OuterOrderDetail;
import com.haierp.service.IErpOrderService;
import com.haierp.service.IInventoryService;
import com.haierp.service.IOuterOrderService;
import com.haierp.service.ISellerService;
import com.haierp.service.ISequenceUtilService;
import com.haierp.service.item.IOuterItemService;
import com.haierp.util.BizResult;
import com.haierp.util.DateUtil;
import com.haierp.util.JsonPageResult;
import com.haierp.util.JsonResult;
import com.haierp.util.ExcelTool.ExcelHelper;
import com.haierp.vo.ErpOrderQueryVO;
import com.haierp.vo.OuterOrderQueryVO;
import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.shiro.ShiroUser;
import com.wangzhixuan.commons.utils.HaiJsonUtils;

/**
 * 
 * @author zhulu
 *
 */
@Controller
@RequestMapping("/outerOrder")
public class OuterOrderController extends BaseController {

	@Autowired
	private IOuterOrderService outerOrderService;
	
	@Autowired
	private ISequenceUtilService sequenceUtilService;
	
	@Autowired
	private IErpOrderService erpOrderService;
	@Autowired
	private IInventoryService inventoryService;
	@Autowired
	private ISellerService sellerService;
	@Autowired
	private IOuterItemService outerItemService;
	@Autowired
	private OuterOrderDetailMapper outerOrderDetailMapper;
	@Autowired
	private OuterOrderMapper outerOrderMapper;
	
	/**
	 * 增加订单
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Object add(OuterOrder outerOrder) {
		JsonResult<String> result = new JsonResult<>();
		if(outerOrder.getId()==null){
			outerOrder.setGmtCreate(new Date());
			outerOrder.setGmtModify(new Date());
			ShiroUser shiroUser = this.getShiroUser();
			outerOrder.setUserCreate(shiroUser.getLoginName());
			outerOrder.setUserModify(shiroUser.getLoginName());//
			outerOrder.setCompanyId(shiroUser.getCompanyId());//所属公司
			outerOrder.setOrderNo("P"+String.format("%0"+2+"d", outerOrder.getPlatformType())+String.format("%0"+4+"d", outerOrder.getSalesId())+"D"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDDHHMMSS)+sequenceUtilService.gainORDSequence());//系统自动生成
			//订单详情
			String outerOrderDetailList = outerOrder.getOrderDetailList();
			if (StringUtils.isNotBlank(outerOrderDetailList)) {
				String s = outerOrderDetailList.replace("&quot;", "\"");
				List<OuterOrderDetail> outerOrderDetails = HaiJsonUtils.toBean(s, new TypeReference<List<OuterOrderDetail>>(){});
				outerOrder.setOuterOrderDetails(outerOrderDetails);
				if(CollectionUtils.isEmpty(outerOrderDetails)){
					return JsonResult.buildFailed("没有商品信息");
				}
			}
			//创建外部订单
			outerOrderService.addOuterOrder(outerOrder);
			//创建订单即刻同步库存到有赞
			List<OuterOrderDetail> outerOrderDetails = outerOrder.getOuterOrderDetails();
			outerOrderDetails.forEach(outerOrderDetail -> {
				//outerItemService.synSkuInventory(outerOrderDetail.getItemId(), outerOrderDetail.getSkuId());
			});
			if(outerOrder.getStatus()==null || outerOrder.getStatus()==0) {
				//生成子订单并配货
				outerOrderService.review(outerOrder.getId(),"ADD");
				//人为建单若没有库存,则重新分配有赞库存给人为订单
				Map<String, Object> clumnMap = new HashMap<>();
				clumnMap.put("outer_order_id", outerOrder.getId());
				List<ErpOrder> erpOrders = erpOrderService.selectByMap(clumnMap);
				if (CollectionUtils.isNotEmpty(erpOrders)) {
					erpOrders.forEach(erpOrder -> {
						if (erpOrder.getStockStatus() == StockUpStatus.INIT.getCode()) {
							Date orderTimeEnd = erpOrder.getOrderTime();
							String orderSkuCode = erpOrder.getSkuCode();
							ErpOrderQueryVO erpOrderQueryVO = new ErpOrderQueryVO();
							erpOrderQueryVO.setSalesId(4);
							erpOrderQueryVO.setEndGmtCreate(orderTimeEnd);
							erpOrderQueryVO.setSkuCode(orderSkuCode);
							erpOrderQueryVO.setIsNeedQuantity(erpOrder.getQuantity());
							List<ErpOrder> listErp = erpOrderService.inventoryYzCount(erpOrderQueryVO);//取最大的释放数据
							if(listErp.size() > 0){
								//先释放需要释放的范围
								for (ErpOrder erpOrder3 : listErp) {
									try {
										inventoryService.releaseInventory(erpOrder3);
									} catch (InventoryException e) {
										e.printStackTrace();
									}
								}
								//分配最后一单释放掉的
								try {
									erpOrderService.lockErpOrder(erpOrder);// 占用已经释放掉的
									erpOrderService.lockErpOrder(listErp.get(listErp.size() - 1));// 分配最后一单释放掉的
								} catch (InventoryException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}
					});
				}
			}
			result.buildIsSuccess(true);
		}else{
			result.buildData("错误数据").buildIsSuccess(false);
		}
		
		return result;
	}
	
	
	/**
	 * 更新订单
	 * 
	 */
	@RequestMapping("/update")
	@ResponseBody
	public Object update(OuterOrder outerOrder) {
		JsonResult<String> result = new JsonResult<>();
		if(outerOrder.getId()!=null) {
			//只有状态为新建的订单才能修改
			OuterOrder selOuterOrder = outerOrderService.selectById(outerOrder.getId());
			if(selOuterOrder==null||selOuterOrder.getStatus()!=OrderStatus.INIT.getCode()){
				return JsonResult.buildFailed("订单不存在或者状态错误");
			}
			//查询是否有发货的订单，有的话订单不能修改
			ErpOrder erpOrderQuery = new ErpOrder();
			erpOrderQuery.setOuterOrderId(outerOrder.getId());
			erpOrderQuery.setStatus(OrderStatus.SENT.getCode());
			int sendOrder = erpOrderService.selectCount(erpOrderQuery);
			if(sendOrder>0){
				return JsonResult.buildFailed("有子订单发货不能修改");
			}
			
			outerOrder.setGmtModify(new Date());
			ShiroUser shiroUser = this.getShiroUser();
			outerOrder.setUserModify(shiroUser.getLoginName());
			outerOrder.setCompanyId(shiroUser.getCompanyId());//主订单修改防止新增 order_detail 和 erp_order 
			//订单详情
			String outerOrderDetailList = outerOrder.getOuterOrderDetailList();
			if (StringUtils.isNotBlank(outerOrderDetailList)) {
				String s = outerOrderDetailList.replace("&quot;", "\"");
				List<OuterOrderDetail> outerOrderDetails = HaiJsonUtils.toBean(s, new TypeReference<List<OuterOrderDetail>>(){});
				outerOrder.setOuterOrderDetails(outerOrderDetails);
			}
			boolean createErpOrder = outerOrderService.updateOuterOrder(outerOrder);
			if(createErpOrder){
				EntityWrapper<ErpOrder> entityWrapper = new EntityWrapper<>();
				entityWrapper.where("outer_order_id = {0} ", outerOrder.getId());
				List<ErpOrder> erpOrders = erpOrderService.selectList(entityWrapper);
				if(CollectionUtils.isNotEmpty(erpOrders)){
					for(ErpOrder erpOrder:erpOrders){
						try {
							//1,释放子订单库存
							inventoryService.releaseInventory(erpOrder);
							//2,删除子订单
							erpOrderService.deleteById(erpOrder);
						} catch (InventoryException e) {
							e.printStackTrace();
						}
					}
				}
				//3,重新生成子订单并分配库存。
				outerOrderService.review(outerOrder.getId(),"ADD");
			}
			result.buildIsSuccess(true);
		} else {
			result.buildData("错误数据").buildIsSuccess(false);
		}
		
		return result;
	}
	
	/**
	 * 查询单个订单
	 */
	@RequestMapping("/query")
	@ResponseBody
	public Object query(Long id) {
		JsonResult<OuterOrder> result = new JsonResult<>();
		OuterOrder outerOrder = outerOrderService.queryOuterOrder(id);

		//如果是代理
		ShiroUser shiroUser = this.getShiroUser();
		Set<String> roles = shiroUser.getRoles();
		if(!roles.contains("telephone")) {
			String tel = outerOrder.getTelephone();
			if(StringUtil.isNotBlank(tel)) {
				outerOrder.setTelephone(tel.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
			}
		}

		return result.buildData(outerOrder).buildIsSuccess(true);
	}
	
	/**
	 * 批量调价查询订单
	 * @return
	 */
	@RequestMapping("/queryOuterOrderList")
	@ResponseBody
	public Object queryOuterOrderList(OuterOrderQueryVO outerOrderQueryVO) {
		if(outerOrderQueryVO.getStatus()!=null&&outerOrderQueryVO.getStatus()==10){//10代表查询全部订单
			outerOrderQueryVO.setStatus(null);
		}
		if(outerOrderQueryVO.getEndGmtCreate()!=null) {
			String endGmtCreateStr = DateUtil.ymdFormat(outerOrderQueryVO.getEndGmtCreate());
			Date endGmtCreate = DateUtil.parseDate(endGmtCreateStr + " 23:59:59");
			outerOrderQueryVO.setEndGmtCreate(endGmtCreate);
		}
		//如果是代理
		ShiroUser shiroUser = this.getShiroUser();
		Set<String> roles = shiroUser.getRoles();
		if(roles.contains("irhdaili")) {
			String[] logingNameArr = shiroUser.getLoginName().split("_");
			if(logingNameArr.length<2 || StringUtils.isBlank(logingNameArr[1])) {
				throw new ErpCommonException("用户权限异常");
			}
			outerOrderQueryVO.setSalesId(Integer.parseInt(logingNameArr[1]));
			Seller seller = sellerService.selectById(outerOrderQueryVO.getSalesId());
			if(seller.getOpenId()!=null) {
				outerOrderQueryVO.setOpenId(seller.getOpenId());
			}
		}
		JsonPageResult<List<OuterOrder>> result = outerOrderService.queryOuterOrderList(outerOrderQueryVO);
		if(!roles.contains("telephone")) {
			List<OuterOrder> outerOrderList = result.getData();
			outerOrderList.forEach(outerOrder -> {
				String tel = outerOrder.getTelephone();
				if(StringUtil.isNotBlank(tel)) {
					outerOrder.setTelephone(tel.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
				}
			});
			result.setNoSaleRoler(true);
		}

		if(roles.contains("irhdaili")) {
			result.setAgentRoler(true);
		}
		if(roles.contains("noexport")) {
			result.setNoEexportRoler(true);
		}
		return result.buildIsSuccess(true);
	}
	
	/**
	 * 删除单个订单
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Object delete(Long id) {
		JsonResult<String> result = new JsonResult<>();
		try {
			OuterOrder outerOrder = outerOrderService.selectById(id);
			if(outerOrder==null||outerOrder.getStatus()!=OrderStatus.CLOSE.getCode()){
				return JsonResult.buildFailed("先关闭才能删除订单");
			}
			outerOrderService.deleteOuterOrder(outerOrder);
		} catch(Exception e) {
			return result.buildIsSuccess(false).buildMsg(e.getMessage());
		}
		return result.buildIsSuccess(true);
	}
	

	/**
	 * 批量关闭订单
	 */
	@RequestMapping("/close")
	@ResponseBody
	public Object close(String orderIds){
		List<String> errorMsg = Lists.newArrayList();
		int i=0;
		if(StringUtils.isNotBlank(orderIds)){
			String s = orderIds.replace("&quot;", "\"");
			List<Long> orderIdList = HaiJsonUtils.toBean(s, new TypeReference<List<Long>>(){});
			for(Long id:orderIdList){
				i++;
				OuterOrder outerOrder = outerOrderService.selectById(id);
				if(outerOrder==null||outerOrder.getStatus()!=OrderStatus.INIT.getCode()){
					errorMsg.add("第"+i+"条不存在或者状态错误,");
				}
				//查询是否有发货的订单，有的话订单不能修改
				ErpOrder erpOrderQuery = new ErpOrder();
				erpOrderQuery.setOuterOrderId(outerOrder.getId());
				erpOrderQuery.setStatus(OrderStatus.SENT.getCode());
				int sendOrder = erpOrderService.selectCount(erpOrderQuery);
				if(sendOrder>0){
					return errorMsg.add("第"+i+"条有子订单发货不能关闭");
				}
				//1、释放子订单库存
				EntityWrapper<ErpOrder> entityWrapper = new EntityWrapper<>();
				entityWrapper.where("outer_order_id = {0} ", outerOrder.getId());
				List<ErpOrder> erpOrders = erpOrderService.selectList(entityWrapper);
				if(CollectionUtils.isNotEmpty(erpOrders)){
					for(ErpOrder erpOrder:erpOrders){
						try {
							//1,释放子订单库存
							inventoryService.releaseInventory(erpOrder);
							//2,更改子订单状态
							erpOrder.setStatus(OrderStatus.CLOSE.getCode());
							erpOrder.setGmtModify(new Date());
							erpOrderService.updateById(erpOrder);
						} catch (InventoryException e) {
							e.printStackTrace();
						}
					}
				}
				//2、更改主子订单状态
				outerOrder.setStatus(OrderStatus.CLOSE.getCode());
				outerOrder.setGmtModify(new Date());
				outerOrderService.updateById(outerOrder);
			}
			StringBuilder rmsg = new StringBuilder();
			if(CollectionUtils.isNotEmpty(errorMsg)){
				for(String a:errorMsg){
					rmsg.append(a);
				}
				return JsonResult.buildFailed(rmsg.toString());
			}else{
				return JsonResult.buildSuccess(null);
			}
			
		}else{
			return JsonResult.buildFailed("没有订单ID");
		}
	}
	
	/**
	 * 查询子订单备货信息
	 */
	@RequestMapping("/erpStockup")
	@ResponseBody
	public Object erpStockup(Long id) {
		JsonResult<List<ErpOrder>> result = new JsonResult<>();
		try {
			if(id!=null){
			EntityWrapper<ErpOrder> entityWrapper = new EntityWrapper<>();
			//entityWrapper.where("outer_order_id = {0} and status <> -1", id);//查询未关闭子订单备货情况
			entityWrapper.where("outer_order_id = {0}", id);  				   //查询所有子订单情况
			List<ErpOrder> erpOrders = erpOrderService.selectList(entityWrapper);
			result.setData(erpOrders);
			}else{
				return JsonResult.buildFailed("没有传ID");
			}
		} catch(Exception e) {
			return result.buildIsSuccess(false).buildMsg(e.getMessage());
		}
		return result.buildIsSuccess(true);
	}

	//手动确认主订单
	@RequestMapping("/reviewOuterOrder")
	@ResponseBody
	public void reviewOuterOrder(Long outerOrderId) {
		outerOrderService.review(outerOrderId,"ADD");
	}
		
	//主订单导出
	@RequestMapping("/OuterOrderExportExcel")
	@ResponseBody
	public ResponseEntity<byte[]> OuterOrderExportExcel(OuterOrderQueryVO OuterOrderQueryVO) throws Exception {
		if(OuterOrderQueryVO.getStartGmtCreate()==null || OuterOrderQueryVO.getEndGmtCreate()==null) {
			throw new ErpCommonException("必须选择创建时间段");
		}
		String startGmtCreateStr = DateUtil.ymdFormat(OuterOrderQueryVO.getStartGmtCreate());
		Date startGmtCreate = DateUtil.parseDate(startGmtCreateStr + " 00:00:00");
		OuterOrderQueryVO.setStartGmtCreate(startGmtCreate);
		String endGmtCreateStr = DateUtil.ymdFormat(OuterOrderQueryVO.getEndGmtCreate());
		Date endGmtCreate = DateUtil.parseDate(endGmtCreateStr + " 23:59:59");
		OuterOrderQueryVO.setEndGmtCreate(endGmtCreate);

		ShiroUser shiroUser = this.getShiroUser();
		Set<String> roles = shiroUser.getRoles();
		
		List<List<Object>> rowDatas = new ArrayList<>();
		List<OuterOrder> outerOrderlist = outerOrderService.queryOuterOrderForExcel(OuterOrderQueryVO);
		if(outerOrderlist != null) {
			for (OuterOrder outerOrder : outerOrderlist) {
				List<Object> list = new ArrayList<>();
				
				list.add(outerOrder.getOrderNo());			//主订单号
				list.add(outerOrder.getSalesName());		//销售员
				list.add(outerOrder.getTotalSalePrice());	//订单金额
				list.add(outerOrder.getGmtCreate());		//下单时间
				list.add(OrderStatus.of(outerOrder.getStatus()).getDescription());  //订单状态
				list.add(outerOrder.getReceiver());			//收件人
				//手机
				if(!roles.contains("telephone")) {
					String tel = outerOrder.getTelephone();
					if(StringUtil.isNotBlank(tel)) {
						list.add(tel.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
					}
				} else {
					list.add(outerOrder.getTelephone());
				}
				list.add(outerOrder.getReceiverState());	//省
				list.add(outerOrder.getReceiverCity());		//市
				list.add(outerOrder.getReceiverDistrict());	//区
				list.add(outerOrder.getAddressDetail());	//详细地址
    			rowDatas.add(list);
			}
		}
		ExcelHelper excelHelper = new ExcelHelper();
    	String[] columnTitles = new String[]{"主订单号", "销售员", "订单金额", "下单时间", "订单状态", "收件人", "手机", "省", "市", "区", "详细地址"};
    	Integer[] columnWidth = new Integer[]{30, 15, 15, 20, 15, 15, 15, 15, 15, 15, 45};
		
    	excelHelper.setOuterOrderToSheet("Father Order", columnTitles, rowDatas, columnWidth);
    	//excelHelper.writeToFile("/Users/liuyang/Work/test.xls");
    	
    	ResponseEntity<byte[]> filebyte = null;
    	ByteArrayOutputStream  out = excelHelper.writeToByteArrayOutputStream();
    	HttpHeaders headers = new HttpHeaders();
    	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    	String fileName = "主订单(" + DateUtil.formatDate(startGmtCreate, "yyyyMMdd") + ").xlsx";
        headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf-8"), "ISO8859-1"));
        
        filebyte = new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.OK);
        out.close();
        excelHelper.close();
        return filebyte; 
	}

	//微信录单确认
	@RequestMapping("/outerOrderReview")
	@ResponseBody
	public Object outerOrderReview() {
		EntityWrapper<OuterOrder> entityWrapper = new EntityWrapper<OuterOrder>();
		entityWrapper.orderBy("order_time", true);
		entityWrapper.where("status=-2");
		List<OuterOrder> outerOrderList = outerOrderService.selectList(entityWrapper);
		if(outerOrderList.size() > 0) {
			outerOrderList.forEach((outerOrder) -> {
				outerOrderService.review(outerOrder.getId(),"ADD");
				
				outerOrder.setStatus(0);
				outerOrderService.updateSelectiveById(outerOrder);
			});
		}
		return JsonResult.buildSuccess(null);
	}

	//错误订单备注
	@RequestMapping("/updateOrderByCheckRemark")
	@ResponseBody
	public Object updateOrderByCheckRemark(OuterOrder outerOrder) {
		if(outerOrder.getId() == null) {
			return JsonResult.buildFailed("订单id错误");
		}
		if(outerOrder.getCheckRemark() == null) {
			return JsonResult.buildFailed("订单备注不能为空");
		}
		outerOrderService.updateSelectiveById(outerOrder);
		return JsonResult.buildSuccess(null);
	}
	
	
	//补录国内物流单号
	@RequestMapping("/updateDetailShipe")
	@ResponseBody
	public Object supplementNoByOrderId(String outerOrderDetailList) {
		if (StringUtils.isNotBlank(outerOrderDetailList)) {
			String s  = outerOrderDetailList.replace("&quot;", "\"");
			List<OuterOrderDetail> detailList = HaiJsonUtils.toBean(s, new TypeReference<List<OuterOrderDetail>>(){});
			for (OuterOrderDetail outerOrderDetail : detailList) {
				OuterOrderDetail detailOne  = outerOrderDetailMapper.selectById(outerOrderDetail.getId());
				detailOne.setDomesticShipe(outerOrderDetail.getDomesticShipe());
				detailOne.setTrackingNo(outerOrderDetail.getTrackingNo());
				outerOrderDetailMapper.updateSelectiveById(detailOne);
			}
		}
			return JsonResult.buildSuccess(null);
	}
	
	/**
	 * 订单明细
	 */
	@RequestMapping("/queryDetailList")
	@ResponseBody
	public Object queryDetailList(Long id) {
		JsonResult<OuterOrder> result = new JsonResult<>();
		if (id == null) {
			throw new RuntimeException("the outerOrder id is null");
		}
		OuterOrder outerOrder = outerOrderMapper.selectById(id);

		if (outerOrder != null) {
			List<OuterOrderDetail> outerOrderDetails = outerOrderDetailMapper.selectOuterOrderDetailByOuterOrderId(id);
			if (outerOrderDetails != null) {
				for (OuterOrderDetail outerOrderDetail : outerOrderDetails) {
					outerOrderDetail.setOrderNo(outerOrder.getOrderNo());
					EntityWrapper<ErpOrder> entityWrapper = new EntityWrapper<>();
					entityWrapper.where("outer_detail_order_id = {0}", outerOrderDetail.getId());
					ErpOrder onlyOne = erpOrderService.selectOne(entityWrapper);
					outerOrderDetail.setErpNo(onlyOne.getErpNo());
					outerOrderDetail.setStatus(onlyOne.getStatus());
					outerOrderDetail.setStockStatus(onlyOne.getStockStatus());
				}
				outerOrder.setOuterOrderDetails(outerOrderDetails);
			}
		}
		return result.buildData(outerOrder).buildIsSuccess(true);
	}
}
